/**
 * 文件名：ArrivalNoticeServiceImpl.java
 * 版权：Copyright Lightkit All Rights Reserved.
 * 描述：到货通知业务处理实现类
 */
package com.lightkits.wms.domain.arrivalnotice.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lightkits.common.db.entity.BdTransaction;
import com.lightkits.common.db.entity.FndEventTypeBase;
import com.lightkits.common.db.entity.FndItemBase;
import com.lightkits.common.db.entity.FndTransactionTypeBase;
import com.lightkits.common.db.entity.FndWorker;
import com.lightkits.common.db.entity.WmDeliveryTicket;
import com.lightkits.common.db.entity.WmDeliveryTicketLine;
import com.lightkits.common.db.entity.WmExecuteLine;
import com.lightkits.common.db.entity.event.BdEvent;
import com.lightkits.common.db.entity.event.BdEventRecord;
import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.model.CheckResult;
import com.lightkits.framework.common.model.IResult;
import com.lightkits.framework.common.utility.date.DateUtil;
import com.lightkits.framework.common.utility.json.JsonUtil;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.object.ParseUtil;
import com.lightkits.framework.common.utility.validate.IntegrityValidator;
import com.lightkits.framework.security.model.UserInfo;
import com.lightkits.framework.soa.client.id.GetGlobalIDRequestType;
import com.lightkits.framework.soa.client.id.IDServiceClient;
import com.lightkits.wms.client.DocumentServiceClient;
import com.lightkits.wms.database.dao.arrivalnotice.ArrivalNoticeMapper;
import com.lightkits.wms.database.model.arrivalnotice.ArrivalInfoModel;
import com.lightkits.wms.database.model.arrivalnotice.ArrivalNoticeLineModel;
import com.lightkits.wms.database.model.arrivalnotice.ArrivalNoticeModel;
import com.lightkits.wms.database.model.arrivalnotice.NewArrivalLineModel;
import com.lightkits.wms.database.model.arrivalnotice.NewSearchModel;
import com.lightkits.wms.database.model.arrivalnotice.ReceiveInfoModel;
import com.lightkits.wms.database.model.arrivalnotice.TicketLinePoNumModel;
import com.lightkits.wms.domain.arrivalnotice.model.TicketStatusEnum;
import com.lightkits.wms.domain.arrivalnotice.model.TicketStructureDTO;
import com.lightkits.wms.domain.arrivalnotice.model.TicketsDTO;
import com.lightkits.wms.domain.arrivalnotice.repo.BdEventRecordRepo;
import com.lightkits.wms.domain.arrivalnotice.repo.BdEventRepo;
import com.lightkits.wms.domain.arrivalnotice.repo.BdTransactionRepo;
import com.lightkits.wms.domain.arrivalnotice.repo.WmDeliveryTicketLineRepo;
import com.lightkits.wms.domain.arrivalnotice.repo.WmDeliveryTicketRepo;
import com.lightkits.wms.domain.arrivalnotice.repo.WmExecuteLineRepo;
import com.lightkits.wms.domain.arrivalnotice.service.ArrivalNoticeService;
import com.lightkits.wms.dto.arrivalnotice.QueryArrivalInfoResponseType;
import com.lightkits.wms.dto.arrivalnotice.QueryArrivalNoticeLineListResponseType;
import com.lightkits.wms.dto.arrivalnotice.QueryArrivalNoticeListResponseType;
import com.lightkits.wms.dto.arrivalnotice.QueryNewArrivalLineResponseType;
import com.lightkits.wms.dto.arrivalnotice.QueryNewSearchResponseType;
import com.lightkits.wms.dto.arrivalnotice.QueryReceiveInfoResponseType;
import com.lightkits.wms.dto.arrivalnotice.model.ArrivalInfoDTO;
import com.lightkits.wms.dto.arrivalnotice.model.ArrivalNoticeDTO;
import com.lightkits.wms.dto.arrivalnotice.model.ArrivalNoticeExecuteServiceDTO;
import com.lightkits.wms.dto.arrivalnotice.model.ArrivalNoticeLineDTO;
import com.lightkits.wms.dto.arrivalnotice.model.ArrivalNoticeServiceDTO;
import com.lightkits.wms.dto.arrivalnotice.model.CancelArrivalNoticeServiceDTO;
import com.lightkits.wms.dto.arrivalnotice.model.ExecuteLineServiceDTO;
import com.lightkits.wms.dto.arrivalnotice.model.ExecuteTicketLineServiceDTO;
import com.lightkits.wms.dto.arrivalnotice.model.NewArrivalLineDTO;
import com.lightkits.wms.dto.arrivalnotice.model.NewSearchDTO;
import com.lightkits.wms.dto.arrivalnotice.model.PrintDTO;
import com.lightkits.wms.dto.arrivalnotice.model.ReceiveInfoDTO;
import com.lightkits.wms.dto.arrivalnotice.model.WmExecuteLineDTO;
import com.lightkits.wms.dto.arrivalnotice.model.WmExecuteTicketDTO;
import com.lightkits.wms.dto.arrivalnotice.model.ticketLineDTO;
import com.lightkits.wms.dto.document.GenerateDocNumRequestType;
import com.lightkits.wms.dto.document.GenerateDocNumResponseType;
import org.assertj.core.util.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author jie.ao@hand-china.com
 * @create 2019-07-03 14:37
 * @desc
 **/
@Service
public class ArrivalNoticeServiceImpl implements ArrivalNoticeService {
    static final int NUM_SIZE = 3;
    static final int NUM_2 = 2;
    private final ArrivalNoticeMapper arrivalNoticeMapper;
    private final DocumentServiceClient documentServiceClient;
    private final BdEventRepo bdEventRepo;
    private final BdEventRecordRepo bdEventRecordRepo;
    private final WmDeliveryTicketRepo wmDeliveryTicketRepo;
    private final WmDeliveryTicketLineRepo wmDeliveryTicketLineRepo;
    private final WmExecuteLineRepo wmExecuteLineRepo;
    private final BdTransactionRepo bdTransactionRepo;
    private final IDServiceClient idServiceClient;
    private static final Logger LOGGER = LoggerFactory.getLogger(ArrivalNoticeServiceImpl.class);

    public ArrivalNoticeServiceImpl(ArrivalNoticeMapper arrivalNoticeMapper,
                                    DocumentServiceClient documentServiceClient,
                                    BdEventRepo bdEventRepo,
                                    BdEventRecordRepo bdEventRecordRepo,
                                    WmDeliveryTicketRepo wmDeliveryTicketRepo,
                                    WmDeliveryTicketLineRepo wmDeliveryTicketLineRepo,
                                    WmExecuteLineRepo wmExecuteLineRepo,
                                    BdTransactionRepo bdTransactionRepo,
                                    IDServiceClient idServiceClient) {
        this.arrivalNoticeMapper = arrivalNoticeMapper;
        this.documentServiceClient = documentServiceClient;
        this.bdEventRepo = bdEventRepo;
        this.bdEventRecordRepo = bdEventRecordRepo;
        this.wmDeliveryTicketRepo = wmDeliveryTicketRepo;
        this.wmDeliveryTicketLineRepo = wmDeliveryTicketLineRepo;
        this.wmExecuteLineRepo = wmExecuteLineRepo;
        this.bdTransactionRepo = bdTransactionRepo;
        this.idServiceClient = idServiceClient;
    }

    @Override
    public QueryArrivalNoticeListResponseType queryArrivalNoticeList(String ticketNum,
                                                                     String organizationName,
                                                                     String partyName) {
        List<ArrivalNoticeModel> models = arrivalNoticeMapper.queryArrivalNoticeList(ticketNum,
                organizationName, partyName);
        List<ArrivalNoticeDTO> list = ObjectUtil.isNullOrEmpty(models) ? new ArrayList<ArrivalNoticeDTO>()
                : models.stream().map(t -> {
                    ArrivalNoticeDTO dto = new ArrivalNoticeDTO();
                    BeanUtils.copyProperties(t, dto);
                    return dto;
                }).collect(Collectors.toList());
        QueryArrivalNoticeListResponseType response = new QueryArrivalNoticeListResponseType();
        response.setArrivalNoticeDTOList(list);
        return response;
    }

    @Override
    public QueryArrivalNoticeLineListResponseType queryArrivalNoticeLineList(String ticketId, String partyId) {
        List<ArrivalNoticeLineModel> models = arrivalNoticeMapper.queryArrivalNoticeLineList(ticketId, partyId);
        List<ArrivalNoticeLineDTO> list = ObjectUtil.isNullOrEmpty(models) ? new ArrayList<ArrivalNoticeLineDTO>()
                : models.stream().map(t -> {
                    ArrivalNoticeLineDTO dto = new ArrivalNoticeLineDTO();
                    BeanUtils.copyProperties(t, dto);
                    return dto;
                }).collect(Collectors.toList());
        QueryArrivalNoticeLineListResponseType response = new QueryArrivalNoticeLineListResponseType();
        response.setArrivalNoticeLineDTOList(list);
        return response;
    }

    @Override
    public QueryArrivalInfoResponseType queryArrivalInfo(String itemId) {
        List<ArrivalInfoModel> models = arrivalNoticeMapper.queryArrivalInfo(itemId);
        List<ArrivalInfoDTO> list = ObjectUtil.isNullOrEmpty(models) ? new ArrayList<ArrivalInfoDTO>()
                : models.stream().map(t -> {
                    ArrivalInfoDTO dto = new ArrivalInfoDTO();
                    BeanUtils.copyProperties(t, dto);
                    return dto;
                }).collect(Collectors.toList());
        QueryArrivalInfoResponseType response = new QueryArrivalInfoResponseType();
        response.setArrivalInfoDTOList(list);
        return response;
    }

    @Override
    public QueryReceiveInfoResponseType queryReceiveInfo(String tickId) {
        List<ReceiveInfoModel> models = arrivalNoticeMapper.queryReceiveInfo(tickId);
        List<ReceiveInfoDTO> list = ObjectUtil.isNullOrEmpty(models) ? null
                : models.stream().map(t -> {
                    ReceiveInfoDTO dto = new ReceiveInfoDTO();
                    BeanUtils.copyProperties(t, dto);
                    return dto;
                }).collect(Collectors.toList());
        QueryReceiveInfoResponseType response = new QueryReceiveInfoResponseType();
        response.setReceiveInfoDTOList(list);
        return response;
    }

    @Override
    public QueryNewArrivalLineResponseType queryNewArrivalLine(String poNum,
                                                               String itemCode,
                                                               String planTime, String planTimeTo) {
        List<NewArrivalLineModel> models = arrivalNoticeMapper.queryNewArrivalLineLOV(poNum, itemCode, planTime,
                planTimeTo);
        List<NewArrivalLineDTO> list = ObjectUtil.isNullOrEmpty(models) ? null
                : models.stream().map(t -> {
                    NewArrivalLineDTO dto = new NewArrivalLineDTO();
                    BeanUtils.copyProperties(t, dto);
                    String deliveryQtySum = t.getDeliveryQtySum();
                    String returnedQty = t.getReturnedQty();
                    String demandQty = t.getDemandQty();
                    BigDecimal remainQty = new BigDecimal(demandQty).subtract(new BigDecimal(deliveryQtySum))
                            .add(new BigDecimal(returnedQty));
                    dto.setRemainQty(remainQty.toString());
                    return dto;
                }).collect(Collectors.toList());
        QueryNewArrivalLineResponseType response = new QueryNewArrivalLineResponseType();
        response.setNewArrivalLineDTOList(list);
        return response;
    }

    @Override
    public QueryNewSearchResponseType queryNewSearchInfo(String partyId) {
        Long paId = ObjectUtil.isNullOrEmpty(partyId) ? null : Long.valueOf(partyId);
        List<NewSearchModel> models = arrivalNoticeMapper.queryNewSearch(paId);
        Map<String, List<String>> itemCodeList = models.stream().collect(Collectors.groupingBy(NewSearchModel::getPoNum,
                Collectors.mapping(NewSearchModel::getItemCode, Collectors.toList())));
        Map<String, List<String>> poNumList = models.stream().collect(Collectors.groupingBy(NewSearchModel::getItemCode,
                Collectors.mapping(NewSearchModel::getPoNum, Collectors.toList())));
        NewSearchDTO dto = new NewSearchDTO();
        dto.setItemListDTO(itemCodeList);
        dto.setPoNumListDTO(poNumList);
        QueryNewSearchResponseType response = new QueryNewSearchResponseType();
        response.setNewSearchDTOList(dto);
        return response;
    }

    @Override
    public IResult saveArrivalNotice(ArrivalNoticeServiceDTO arrivalNoticeServiceDTO,
                                     TicketStructureDTO insertDTO,
                                     TicketStructureDTO modifyDTO) {
        //校验数据的有效性
        IResult result = checkIntegrity(arrivalNoticeServiceDTO);
        if (!result.isSuccessful()) {
            return result;
        }
        //判断其是更新还是插入
        result = fillData(arrivalNoticeServiceDTO, insertDTO, modifyDTO);
        if (!result.isSuccessful()) {
            return result;
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public IResult executeArrivalNoticeList(List<ArrivalNoticeExecuteServiceDTO> serviceDTOList) {
        IResult result = IResult.success();
        Optional<ArrivalNoticeExecuteServiceDTO> flag = serviceDTOList.stream()
                .filter(t -> TicketStatusEnum.CANCEL.getValue().equalsIgnoreCase(t.getTicketStatus())
                || t.getTagControl())
                .findFirst();
        //存在已取消的状态的到货单，存在开启条码管理的到货单
        if (flag.isPresent()) {
            result.setMessage("CANNOT_USE_THIS_BUTTON");
            result.setSuccessful(false);
            return result;
        }
        List<String> ticketIdList = serviceDTOList.stream()
                .map(ArrivalNoticeExecuteServiceDTO::getTicketId).collect(Collectors.toList());
        List<WmDeliveryTicket> deliveryTicketList = new WmDeliveryTicket()
                .selectList(new EntityWrapper<WmDeliveryTicket>()
                        .in(WmDeliveryTicket.ID, ticketIdList));
        deliveryTicketList.forEach(t -> t.setTicketStatus(TicketStatusEnum.EXECUTE.getValue()));
        wmDeliveryTicketRepo.updateBatch(deliveryTicketList);
        // 创建事件
        GetGlobalIDRequestType getIdRequest = new GetGlobalIDRequestType();
        getIdRequest.setCount(serviceDTOList.size());
        List<Long> ids = idServiceClient.getGlobalId(getIdRequest).getIds();
        FndEventTypeBase typeBase = new FndEventTypeBase()
                .selectOne(new EntityWrapper<FndEventTypeBase>().eq(FndEventTypeBase.EVENT_TYPE_CODE,
                        "WM_ITEM_RECEIVE"));
        Long typeBaseId = typeBase.getId();
        Map<String, BdEvent> bdEventMap = serviceDTOList.stream()
                .collect(Collectors
                        .toMap(ArrivalNoticeExecuteServiceDTO::getTicketId, t -> {
                            BdEvent event = new BdEvent();
                            event.setEventTypeCode("WM_ITEM_RECEIVE");
                            event.setOrganizationId(Long.valueOf(t.getOrganizationId()));
                            event.setEventTypeId(typeBaseId);
                            event.setRemark(t.getRemark());
                            return event;
                        }));
        List<BdEvent> values = Lists.newArrayList(bdEventMap.values());
        for (int i = 0; i < values.size(); i++) {
            values.get(i).setEventRequestId(ids.get(i));
        }
        List<BdEvent> events = bdEventMap.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());
        bdEventRepo.insertBatch(events);
        //创建仓储执行明细行
        List<WmExecuteLine> wmExecuteLineList = new ArrayList<>();
        SimpleDateFormat df = new SimpleDateFormat(DateUtil.DEFAULT_DATETIME_PATTERN);
        for (ArrivalNoticeExecuteServiceDTO t : serviceDTOList) {
            List<ticketLineDTO> ticketLineDTOList = t.getTicketLineDTOList();
            List<WmExecuteLine> collect = ticketLineDTOList.stream().map(m -> {
                WmExecuteLine executeLine = new WmExecuteLine();
                executeLine.setDocumentType("DLIRTICKET");
                executeLine.setDocumentId(Long.valueOf(t.getTicketId()));
                executeLine.setDocumentLineId(Long.valueOf(m.getTicketLineId()));
                executeLine.setExecuteType(TicketStatusEnum.RECIEVED.getValue());
                executeLine.setItemId(Long.valueOf(m.getItemId()));
                executeLine.setUom(m.getUom());
                executeLine.setExecutedQty(new BigDecimal(m.getDeliveryQty()));
                try {
                    Date date = df.parse(df.format(new Date()));
                    executeLine.setExecutedTime(date);
                } catch (Exception e) {
                    LOGGER.error("ArrivalNoticeServiceImpl.dateFormat", e);
                    throw new LightKitsBizException(e);
                }
                executeLine.setLotNumber(m.getLotCode());
                executeLine.setEventId(bdEventMap.get(m.getTicketId()).getId());
                return executeLine;
            }).collect(Collectors.toList());
            wmExecuteLineList.addAll(collect);
        }
        wmExecuteLineRepo.insertBatch(wmExecuteLineList);
        //创建快照
        List<BdEventRecord> eventRecordList = getBdEventRecords(wmExecuteLineList);
        bdEventRecordRepo.insertBatch(eventRecordList);
        //创建事务
        FndTransactionTypeBase transactionTypeBase = new FndTransactionTypeBase()
                .selectOne(new EntityWrapper<FndTransactionTypeBase>()
                .eq(FndTransactionTypeBase.TRANSACTION_TYPE_CODE, "WMS001"));
        if (ObjectUtil.isEmpty(transactionTypeBase)) {
            result.setSuccessful(false);
            result.setMessage("找不到事务code");
            return result;
        }
        Long id = transactionTypeBase.getId();
        List<BdTransaction> transactionList = serviceDTOList.stream().map(t -> {
            BdTransaction transaction = new BdTransaction();
            transaction.setTransactionTypeCode("WMS001");
            transaction.setOrganizationId(Long.valueOf(t.getOrganizationId()));
            transaction.setTransactionTime(new Date());
            transaction.setTransactionTypeId(id);
            return transaction;
        }).collect(Collectors.toList());
        bdTransactionRepo.insertBatch(transactionList);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public IResult executeArrivalNotice(ExecuteLineServiceDTO serviceDTO) {
        IResult result = IResult.success();
        if (ObjectUtil.isEmpty(serviceDTO)) {
            result.setMessage("请选中一行到货单再执行");
            result.setSuccessful(false);
            return result;
        }
        // 判断状态不能为cancel
        if (TicketStatusEnum.CANCEL.getValue().equalsIgnoreCase(serviceDTO.getTicketStatus())) {
            result.setMessage("CANNOT_USE_THIS_BUTTON");
            result.setSuccessful(false);
            return result;
        }
        //判断本次接收数量等于本次到货数量
        List<ExecuteTicketLineServiceDTO> ticketLineServiceDTOList = serviceDTO.getTicketLineServiceDTOList();
        if (!ObjectUtil.isNullOrEmpty(ticketLineServiceDTOList)) {
            ticketLineServiceDTOList.forEach(t -> {
                List<WmExecuteLineDTO> executeLineDTOS = t.getWmExecuteLineDTOList();
                if (!ObjectUtil.isNullOrEmpty(executeLineDTOS)) {
                    BigDecimal executedQtySum = executeLineDTOS.stream()
                            .map(WmExecuteLineDTO::getExecutedQty)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    if (executedQtySum.compareTo(t.getReceivedQty()) != 0) {
                        result.setMessage("到货总数不等于接收数量");
                        result.setSuccessful(false);
                    }
                }
            });
        }
        if (!result.isSuccessful()) {
            return result;
        }
        // 查询到货信息
        WmDeliveryTicket deliveryTicket = new WmDeliveryTicket().selectById(serviceDTO.getTicketId());
        deliveryTicket.setTicketStatus(TicketStatusEnum.EXECUTE.getValue());
        wmDeliveryTicketRepo.update(deliveryTicket);
        //创建事件
        GetGlobalIDRequestType getIdRequest = new GetGlobalIDRequestType();
        Long id = idServiceClient.getGlobalId(getIdRequest).getId();
        FndEventTypeBase typeBase = new FndEventTypeBase()
                .selectOne(new EntityWrapper<FndEventTypeBase>().eq(FndEventTypeBase.EVENT_TYPE_CODE,
                        "WM_ITEM_RECEIVE"));
        Long typeBaseId = typeBase.getId();
        BdEvent event = new BdEvent();
        event.setEventTypeCode("WM_ITEM_RECEIVE");
        event.setOrganizationId(Long.valueOf(serviceDTO.getOrganizationId()));
        event.setEventTypeId(typeBaseId);
        event.setRemark(serviceDTO.getRemark());
        event.setEventRequestId(id);
        bdEventRepo.insert(event);
        // 创建仓储执行明细行
        List<WmDeliveryTicketLine> ticketLines = new WmDeliveryTicketLine()
                .selectList(new EntityWrapper<WmDeliveryTicketLine>().eq(WmDeliveryTicketLine.TICKET_ID,
                        serviceDTO.getTicketId()));
        List<WmExecuteTicketDTO> executeLineDTOList = new ArrayList<>();
        for (ExecuteTicketLineServiceDTO dto : ticketLineServiceDTOList) {
            List<WmExecuteLineDTO> lineDTOList = dto.getWmExecuteLineDTOList();
            if (!ObjectUtil.isNullOrEmpty(lineDTOList)) {
                List<WmExecuteTicketDTO> ticketDTOS = lineDTOList.stream().map(t -> {
                    WmExecuteTicketDTO dto1 = new WmExecuteTicketDTO();
                    BeanUtils.copyProperties(t, dto1);
                    dto1.setUom(dto.getUom());
                    return dto1;
                }).collect(Collectors.toList());
                executeLineDTOList.addAll(ticketDTOS);
            }
        }
        List<WmExecuteLine> wmExecuteLineList = executeLineDTOList.stream().map(m -> {
            WmExecuteLine executeLine = new WmExecuteLine();
            executeLine.setDocumentType("DLIRTICKET");
            executeLine.setDocumentId(Long.valueOf(serviceDTO.getTicketId()));
            executeLine.setDocumentLineId(m.getTicketLineId());
            executeLine.setExecuteType(TicketStatusEnum.RECIEVED.getValue());
            executeLine.setItemId(ParseUtil.tryLong(m.getItemId()));
            executeLine.setUom(m.getUom());
            executeLine.setExecutedQty(m.getExecutedQty());
            executeLine.setExecutedTime(new Date());
            executeLine.setLotNumber(m.getLotNumber());
            executeLine.setEventId(event.getId());
            return executeLine;
        }).collect(Collectors.toList());
        wmExecuteLineRepo.insertBatch(wmExecuteLineList);
        //创建快照
        List<BdEventRecord> eventRecordList = getBdEventRecords(wmExecuteLineList);
        bdEventRecordRepo.insertBatch(eventRecordList);
        //创建事务
        FndTransactionTypeBase transactionTypeBase = new FndTransactionTypeBase()
                .selectOne(new EntityWrapper<FndTransactionTypeBase>()
                        .eq(FndTransactionTypeBase.TRANSACTION_TYPE_CODE, "WMS001"));
        if (ObjectUtil.isEmpty(transactionTypeBase)) {
            result.setSuccessful(false);
            result.setMessage("找不到事务编码");
            return result;
        }
        Long transactionId = transactionTypeBase.getId();
        List<Long> tickLineIdList = wmExecuteLineList.stream()
                .map(WmExecuteLine::getDocumentLineId).collect(Collectors.toList());
        List<TicketLinePoNumModel> poNumModels = arrivalNoticeMapper.queryTicketLinePoNum(tickLineIdList);
        List<BdTransaction> transactionList = wmExecuteLineList.stream().map(t -> {
            BdTransaction transaction = new BdTransaction();
            transaction.setTransactionTypeId(transactionId);
            transaction.setTransactionTypeCode("WMS001");
            transaction.setOrganizationId(ParseUtil.tryLong(serviceDTO.getOrganizationId()));
            transaction.setTransactionTime(t.getCreationDate());
            transaction.setItemId(t.getItemId());
            transaction.setTransactionQty(t.getExecutedQty());
            transaction.setTransactionUom(t.getUom());
            transaction.setTransactionDate(new Date());
            transaction.setDocumentTypeCode("WM_DELIVERY_TICKET");
            transaction.setDocumentId(t.getDocumentId());
            transaction.setDocumentLineId(t.getDocumentLineId());
            transaction.setDocumentNum(deliveryTicket.getTicketNum());
            //todo
            transaction.setSourceDocTypeId(ParseUtil.tryLong(serviceDTO.getTicketId()));
            transaction.setSourceDocTypeCode("PO");
            Optional<WmDeliveryTicketLine> ticketLineOptional = ticketLines.stream()
                    .filter(m -> m.getId().equals(t.getDocumentLineId()))
                    .findFirst();
            assert ticketLineOptional.isPresent();
            transaction.setSourceDocId(ticketLineOptional.get().getPoId());
            transaction.setSourceDocLineId(ticketLineOptional.get().getPoLineId());
            Optional<String> poNumOptional = poNumModels.stream()
                    .filter(p -> p.getTicketLineId().equals(t.getDocumentLineId()))
                    .map(TicketLinePoNumModel::getPoNum)
                    .findFirst();
            assert poNumOptional.isPresent();
            transaction.setSourceDocNum(poNumOptional.get());
            //transaction.setWmAreaId();
            return transaction;
        }).collect(Collectors.toList());
        bdTransactionRepo.insertBatch(transactionList);
        return result;
    }

    /**
     * 赋值到快照表
     * @param wmExecuteLineList 仓储执行List
     * @return List<BdEventRecord>
     */
    private List<BdEventRecord> getBdEventRecords(List<WmExecuteLine> wmExecuteLineList) {
        return wmExecuteLineList.stream().map(t -> {
            BdEventRecord record = new BdEventRecord();
            record.setEventId(t.getDocumentId());
            record.setObjectType("WM_EXECUTE_LINE");
            record.setObjectId(t.getId());
            String json = JsonUtil.toString(t);
            record.setSnapshotRecord(json);
            return record;
        }).collect(Collectors.toList());
    }

    /**
     * 插入数据库操作
     * @param insertDTO 新增list
     * @param modifyDTO 修改list
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertDate(TicketStructureDTO insertDTO, TicketStructureDTO modifyDTO) {
        List<BdEventRecord> bdEventRecordList;
        if (!ObjectUtil.isEmpty(insertDTO.getBdEvent())) {
            List<WmDeliveryTicket> ticketList = insertDTO.getTicketList();
            List<WmDeliveryTicketLine> ticketLineList = insertDTO.getTicketLineList();
            BdEvent bdEvent = insertDTO.getBdEvent();
            //新增头
            wmDeliveryTicketRepo.insertBatch(ticketList);
            //把头id赋值到行上
            if (ticketList.size() == 1) { //只存在一种条码状态标识状态
                WmDeliveryTicket ticket = ticketList.get(0);
                Long ticketId = ticket.getId();
                ticketLineList.forEach(t -> {
                    t.setTicketId(ticketId);
                });
            } else { //存在两种
                //启动条码管理
                Optional<WmDeliveryTicket> ticketListY = ticketList.stream()
                        .filter(t -> "-1".equals(t.getTicketNum().substring(t.getTicketNum().length() - NUM_2)))
                        .findFirst();
                //未启动条码管理
                Optional<WmDeliveryTicket> ticketListN = ticketList.stream()
                        .filter(t -> "-2".equals(t.getTicketNum().substring(t.getTicketNum().length() - NUM_2)))
                        .findFirst();
                assert ticketListN.isPresent();
                assert ticketListY.isPresent();
                Long idY = ticketListY.get().getId();
                Long idN = ticketListN.get().getId();
                //取到itemIdList
                List<Long> itemIdList = ticketLineList.stream()
                        .map(WmDeliveryTicketLine::getItemId)
                        .collect(Collectors.toList());
                List<FndItemBase> fndItemYList = new FndItemBase()
                        .selectList(new EntityWrapper<FndItemBase>()
                                .eq(FndItemBase.TAG_CONTROL, true)
                                .in(FndItemBase.ITEM_ID, itemIdList));

                List<FndItemBase> fndItemNList = new FndItemBase()
                        .selectList(new EntityWrapper<FndItemBase>()
                                .in(FndItemBase.ITEM_ID, itemIdList)
                                .andNew()
                                .eq(FndItemBase.TAG_CONTROL, false)
                                .or()
                                .isNull(FndItemBase.TAG_CONTROL));
                //给对应启动条码管理状态上复制ticketId
                ticketLineList.stream()
                        .filter(t -> fndItemNList.stream().anyMatch(i -> i.getItemId().equals(t.getItemId())))
                        .forEach(t -> t.setTicketId(idN));
                ticketLineList.stream()
                        .filter(t -> fndItemYList.stream().anyMatch(i -> i.getItemId().equals(t.getItemId())))
                        .forEach(t -> t.setTicketId(idY));
            }
            //新增行
            wmDeliveryTicketLineRepo.insertBatch(ticketLineList);
            //新增事件
            bdEventRepo.insert(bdEvent);
            Long bdEventId = bdEvent.getId();
            bdEventRecordList = getBdEventRecordList(ticketLineList, bdEventId);
            //新增快照
            bdEventRecordRepo.insertBatch(bdEventRecordList);
        }
        //修改
        if (!ObjectUtil.isEmpty(modifyDTO.getBdEvent())) {
            List<WmDeliveryTicketLine> ticketLineList = modifyDTO.getTicketLineList();
            wmDeliveryTicketLineRepo.updateBatch(ticketLineList);
            BdEvent bdEvent = modifyDTO.getBdEvent();
            //新增事件
            bdEventRepo.insert(bdEvent);
            Long bdEventId = bdEvent.getId();
            bdEventRecordList = getBdEventRecordList(ticketLineList, bdEventId);
            //新增快照
            bdEventRecordRepo.insertBatch(bdEventRecordList);
        }
    }

    @Override
    public IResult cancelArrivalNotice(CancelArrivalNoticeServiceDTO cancelArrivalNoticeServiceDTO) {
        IResult result = IResult.success();
        String status = cancelArrivalNoticeServiceDTO.getTicketStatus();
        if (TicketStatusEnum.CANCEL.getValue().equalsIgnoreCase(status)
                || TicketStatusEnum.EXECUTE.getValue().equalsIgnoreCase(status)) {
            result.setMessage("CANNOT_USE_THIS_BUTTON");
            result.setSuccessful(false);
            return result;
        }
        String ticketId = cancelArrivalNoticeServiceDTO.getTicketId();
        WmDeliveryTicket ticket = new WmDeliveryTicket().selectById(ticketId);
        if (ObjectUtil.isEmpty(ticket)) {
            result.setMessage("找不到该到货单");
            result.setSuccessful(false);
            return result;
        }
        ticket.setTicketStatus(TicketStatusEnum.CANCEL.getValue());
        wmDeliveryTicketRepo.update(ticket);
        //创建事件
        BdEvent bdEvent = new BdEvent();
        bdEvent.setEventTypeCode("WM_DELIVERY_TICKET_CANCELED");
        GetGlobalIDRequestType getIdRequest = new GetGlobalIDRequestType();
        Long id = idServiceClient.getGlobalId(getIdRequest).getId();
        bdEvent.setEventRequestId(id);
        String organizationId = cancelArrivalNoticeServiceDTO.getOrganizationId();
        if (!ObjectUtil.isEmpty(organizationId)) {
            bdEvent.setOrganizationId(Long.valueOf(organizationId));
        }
        bdEvent.setRemark(cancelArrivalNoticeServiceDTO.getRemark());
        FndEventTypeBase eventTypeBase = new FndEventTypeBase().selectOne(new EntityWrapper<FndEventTypeBase>()
                .eq(FndEventTypeBase.EVENT_TYPE_CODE, "WM_DELIVERY_TICKET_CANCELED"));
        Long typeBaseId = eventTypeBase.getId();
        bdEvent.setEventTypeId(typeBaseId);
        bdEvent.setWorkerId(getFndWorker().getId());
        bdEventRepo.insert(bdEvent);
        //创建快照
        List<WmDeliveryTicketLine> ticketLineList = new WmDeliveryTicketLine()
                .selectList(new EntityWrapper<WmDeliveryTicketLine>()
                .eq(WmDeliveryTicketLine.TICKET_ID, ticketId));
        Long eventId = bdEvent.getId();
        List<WmDeliveryTicketLine> ticketLines = new WmDeliveryTicketLine()
                .selectList(new EntityWrapper<WmDeliveryTicketLine>().eq(WmDeliveryTicketLine.TICKET_ID, ticket));
        TicketsDTO dto = new TicketsDTO();
        dto.setTicket(ticket);
        dto.setTicketLines(ticketLines);
        String json = JsonUtil.toString(dto);
        List<BdEventRecord> bdEventRecords = ticketLineList.stream().map(t -> {
            BdEventRecord record = new BdEventRecord();
            record.setEventId(eventId);
            record.setObjectType("WM_DELIVERY_TICKET_LINE");
            record.setObjectId(t.getId());
            record.setSnapshotRecord(json);
            return record;
        }).collect(Collectors.toList());
        bdEventRecordRepo.insertBatch(bdEventRecords);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public IResult printArrivalNotice(PrintDTO printDTO) {
        IResult result = IResult.success();
        String ticketId = printDTO.getTicketId();
        WmDeliveryTicket ticket = new WmDeliveryTicket().selectById(ticketId);
        String ticketStatus = ticket.getTicketStatus();
        if (!"NEW".equalsIgnoreCase(ticketStatus)) {
            result.setSuccessful(false);
            result.setMessage("该状态不能执行");
            return result;
        }
        ticket.setTicketStatus("EXPORTED");
        wmDeliveryTicketRepo.update(ticket);
        BdEvent bdEvent = new BdEvent();
        bdEvent.setEventTypeCode("PRINT_ARRIVAL_TICKET");
        GetGlobalIDRequestType getIdRequest = new GetGlobalIDRequestType();
        Long id = idServiceClient.getGlobalId(getIdRequest).getId();
        bdEvent.setEventRequestId(id);
        bdEvent.setOrganizationId(ParseUtil.tryLong(printDTO.getOrganizationId()));
        bdEvent.setRemark(printDTO.getRemark());
        FndEventTypeBase eventTypeBase = new FndEventTypeBase().selectOne(new EntityWrapper<FndEventTypeBase>()
                .eq(FndEventTypeBase.EVENT_TYPE_CODE, "PRINT_ARRIVAL_TICKET"));
        if (ObjectUtil.isEmpty(eventTypeBase)) {
            result.setSuccessful(false);
            result.setMessage("找不到事件类型编码");
            return result;
        }
        Long typeBaseId = eventTypeBase.getId();
        bdEvent.setEventTypeId(typeBaseId);
        bdEvent.setWorkerId(getFndWorker().getId());
        bdEventRepo.insert(bdEvent);
        //创建快照
        Long eventId = bdEvent.getId();
        BdEventRecord record = new BdEventRecord();
        record.setEventId(eventId);
        record.setObjectType("WM_DELIVERY_TICKET");
        record.setObjectId(ParseUtil.tryLong(ticketId));
        bdEventRecordRepo.insert(record);
        return result;
    }

    /**
     * 给快照表赋值
     *
     * @param ticketLineList 到货行表
     * @param bdEventId      事件id
     * @return List<BdEventRecord>
     */
    private List<BdEventRecord> getBdEventRecordList(List<WmDeliveryTicketLine> ticketLineList, Long bdEventId) {
        List<BdEventRecord> bdEventRecordList;
        bdEventRecordList = ticketLineList.stream().map(t -> {
            BdEventRecord b = new BdEventRecord();
            b.setEventId(bdEventId);
            b.setObjectId(t.getId());
            b.setObjectType("WM_DELIVERY_TICKET_LINE");
            b.setRecordType("DELIVERY_QTY");
            b.setKeyValue(String.valueOf(t.getDeliveryQty()));
            return b;
        }).collect(Collectors.toList());
        return bdEventRecordList;
    }


    /**
     * 判断其是更新还是插入，赋值
     *
     * @param arrivalNoticeServiceDTO 前端传来的参数
     * @param insertDTO               新增list
     * @param modifyDTO               修改list
     * @return result
     */
    private IResult fillData(ArrivalNoticeServiceDTO arrivalNoticeServiceDTO,
                             TicketStructureDTO insertDTO,
                             TicketStructureDTO modifyDTO) {
        IResult result;
        //新增
        String ticketId = arrivalNoticeServiceDTO.getTicketId();
        if (ObjectUtil.isEmpty(ticketId)) {
            result = fillAddData(arrivalNoticeServiceDTO, insertDTO);
            if (!result.isSuccessful()) {
                return result;
            }
        } else { //修改
            result = fillUpdateData(arrivalNoticeServiceDTO, modifyDTO);
            if (!result.isSuccessful()) {
                return result;
            }
        }
        return result;
    }

    /**
     * 修改赋值List
     *
     * @param dto       update
     * @param modifyDTO updateDTO
     * @return result
     */
    private IResult fillUpdateData(ArrivalNoticeServiceDTO dto, TicketStructureDTO modifyDTO) {
        List<ticketLineDTO> lineDTOList = dto.getTicketLineDTOList();
        List<String> ticketLineIdList = lineDTOList.stream()
                .map(ticketLineDTO::getTicketLineId)
                .collect(Collectors.toList());
        List<WmDeliveryTicketLine> wmDeliveryTicketLines = new WmDeliveryTicketLine()
                .selectList(new EntityWrapper<WmDeliveryTicketLine>()
                        .in(WmDeliveryTicketLine.ID, ticketLineIdList));
        //给DeliveryQty赋值
        wmDeliveryTicketLines.forEach(t ->
                t.setDeliveryQty(new BigDecimal(lineDTOList
                        .stream()
                        .filter(l -> t.getId().equals(l.getTicketId()))
                        .findFirst().get().getDeliveryQty())));
        modifyDTO.setTicketLineList(wmDeliveryTicketLines);
        //创建事件
        BdEvent bdEvent = new BdEvent();
        bdEvent.setEventTypeCode("ARRIAL_TICKET_CREATED");
        FndWorker fndWorker = getFndWorker();
        bdEvent.setWorkerId(fndWorker.getId());
        bdEvent.setOrganizationId(Long.valueOf(dto.getOrganizationId()));
        bdEvent.setRemark(dto.getRemark());
        modifyDTO.setBdEvent(bdEvent);
        return IResult.success();
    }

    /**
     * 新增赋值list
     *
     * @param dto       addList
     * @param insertDTO insertDTO
     * @return result
     */
    private IResult fillAddData(ArrivalNoticeServiceDTO dto, TicketStructureDTO insertDTO) {
        IResult result = IResult.success();
        FndWorker fndWorker = getFndWorker();
        if (ObjectUtil.isEmpty(fndWorker)) {
            result.setSuccessful(false);
            result.setMessage("Can not find the worker");
            return result;
        }
        //判断到货行中条码管理信息
        List<ticketLineDTO> lineDTOList = dto.getTicketLineDTOList();
        //判断到货行中存在是否的条件
        List<ticketLineDTO> barCode1 = lineDTOList.stream()
                .filter(ticketLineDTO::getBarCodeFlag)
                .collect(Collectors.toList());
        List<ticketLineDTO> barCode2 = lineDTOList.stream()
                .filter(t -> !t.getBarCodeFlag())
                .collect(Collectors.toList());
        GenerateDocNumRequestType request = new GenerateDocNumRequestType();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        request.setCount(1);
        request.setSize(NUM_SIZE);
        request.setType("AO");
        request.setField1(df.format(new Date()));
        GenerateDocNumResponseType response = documentServiceClient.generateDocNumber(request);
        if (!response.isSuccessful()) {
            result.setSuccessful(false);
            result.setMessage(response.getMessage());
            return result;
        }
        String num = response.getDocNumList().get(0);
        List<WmDeliveryTicket> ticketList = new ArrayList<>();
        List<WmDeliveryTicketLine> ticketLineList;
        boolean flag = !ObjectUtil.isNullOrEmpty(barCode1) && !ObjectUtil.isNullOrEmpty(barCode2);
        //存在两种
        if (flag) {
            //赋值到两个头，(接收条码管理，不接收条码管理)
            WmDeliveryTicket ticketY = new WmDeliveryTicket();
            WmDeliveryTicket ticketN = new WmDeliveryTicket();
            copyTicketValue(dto, ticketY);
            copyTicketValue(dto, ticketN);
            ticketY.setTicketNum(num + "-1");
            ticketN.setTicketNum(num + "-2");
            ticketN.setTicketType("SELF");
            ticketY.setTicketType("SELF");
            ticketList.add(ticketN);
            ticketList.add(ticketY);
            //赋值到货行
            ticketLineList = getTicketLineList(lineDTOList);
            insertDTO.setTicketLineList(ticketLineList);
            insertDTO.setTicketList(ticketList);
        } else {
            //赋值到货头
            WmDeliveryTicket ticket = new WmDeliveryTicket();
            copyTicketValue(dto, ticket);
            ticket.setTicketNum(num);
            ticket.setTicketType("SELF");
            ticketList.add(ticket);
            //赋值到货行
            ticketLineList = getTicketLineList(lineDTOList);
            insertDTO.setTicketLineList(ticketLineList);
            insertDTO.setTicketList(ticketList);
        }
        //赋值事件
        BdEvent bdEvent = new BdEvent();
        GetGlobalIDRequestType getIdRequest = new GetGlobalIDRequestType();
        Long id = idServiceClient.getGlobalId(getIdRequest).getId();
        bdEvent.setEventTypeCode("ARRIVAL_TICKET_CREATED");
        FndEventTypeBase eventTypeBase = new FndEventTypeBase().selectOne(new EntityWrapper<FndEventTypeBase>()
                .eq(FndEventTypeBase.EVENT_TYPE_CODE, "ARRIVAL_TICKET_CREATED"));
        bdEvent.setEventTypeId(eventTypeBase.getId());
        bdEvent.setEventRequestId(id);
        bdEvent.setWorkerId(fndWorker.getId());
        bdEvent.setOrganizationId(Long.valueOf(dto.getOrganizationId()));
        bdEvent.setRemark(dto.getRemark());
        insertDTO.setBdEvent(bdEvent);
        return result;
    }

    /**
     * 获取当前用户work
     *
     * @return FndWorker
     */
    private FndWorker getFndWorker() {
        //得到当前用户的workId
        return new FndWorker()
                .selectOne(new EntityWrapper<FndWorker>()
                        .eq(FndWorker.WORKER_NUMBER, UserInfo.current().getWorkerNumber()));
    }

    /**
     * 到货行表赋值
     *
     * @param lineDTOList source
     * @return List<WmDeliveryTicketLine> target
     */
    private List<WmDeliveryTicketLine> getTicketLineList(List<ticketLineDTO> lineDTOList) {
        List<WmDeliveryTicketLine> ticketLineList = new ArrayList<>();
        for (int i = 0; i < lineDTOList.size(); i++) {
            WmDeliveryTicketLine line = new WmDeliveryTicketLine();
            if (!ObjectUtil.isNullOrEmpty(lineDTOList.get(i).getTicketId())) {
                line.setTicketId(Long.valueOf(lineDTOList.get(i).getTicketId()));
            }
            line.setWmDeliveryTicketLineNum(String.valueOf(i + 1));
            if (!ObjectUtil.isNullOrEmpty(lineDTOList.get(i).getPoId())) {
                line.setPoId(Long.valueOf(lineDTOList.get(i).getPoId()));
            }
            if (!ObjectUtil.isNullOrEmpty(lineDTOList.get(i).getPoLineId())) {
                line.setPoLineId(Long.valueOf(lineDTOList.get(i).getPoLineId()));
            }
            if (!ObjectUtil.isEmpty(lineDTOList.get(i).getDemandDate())) {
                if (DateUtil.isDate(lineDTOList.get(i).getDemandDate(), DateUtil.DEFAULT_DATE_PATTERN)) {
                    try {
                        Date date = DateUtil.toDate(lineDTOList.get(i).getDemandDate(), DateUtil.DEFAULT_DATE_PATTERN);
                        line.setDemandDate(date);
                    } catch (Exception e) {
                        LOGGER.error("ArrivalNoticeServiceImpl.dateFormat", e);
                        throw new LightKitsBizException(e);
                    }
                } else {
                    LOGGER.error("ArrivalNoticeServiceImpl.dateFormat", "DemandDate Format Error");
                }
            } else {
                line.setDemandDate(null);
            }
            if (!ObjectUtil.isNullOrEmpty(lineDTOList.get(i).getItemId())) {
                line.setItemId(Long.valueOf(lineDTOList.get(i).getItemId()));
            }
            line.setUom(lineDTOList.get(i).getUom());
            if (!ObjectUtil.isNullOrEmpty(lineDTOList.get(i).getDeliveryQty())) {
                line.setDeliveryQty(new BigDecimal(lineDTOList.get(i).getDeliveryQty()));
            }
            if (!ObjectUtil.isNullOrEmpty(lineDTOList.get(i).getReturnedQty())) {
                line.setReturnedQty(new BigDecimal(lineDTOList.get(i).getReturnedQty()));
            }
            if (!ObjectUtil.isNullOrEmpty(lineDTOList.get(i).getReceiveWarehouseId())) {
                line.setReceiveWarehouseId(Long.valueOf(lineDTOList.get(i).getReceiveWarehouseId()));
            }
            line.setLotCode(lineDTOList.get(i).getLotCode());
            line.setLineControl(lineDTOList.get(i).getLineControl());
            ticketLineList.add(line);
        }
//        ticketLineList = lineDTOList.stream().map(t -> {
//            WmDeliveryTicketLine line = new WmDeliveryTicketLine();
//            if (!ObjectUtil.isNullOrEmpty(t.getTicketId())) {
//                line.setTicketId(Long.valueOf(t.getTicketId()));
//            }
//            line.setWmDeliveryTicketLineNum();
//            if (!ObjectUtil.isNullOrEmpty(t.getPoId())) {
//                line.setPoId(Long.valueOf(t.getPoId()));
//            }
//            if (!ObjectUtil.isNullOrEmpty(t.getPoLineId())) {
//                line.setPoLineId(Long.valueOf(t.getPoLineId()));
//            }
//            if (!ObjectUtil.isEmpty(t.getDemandDate())) {
//                if (DateUtil.isDate(t.getDemandDate(), DateUtil.DEFAULT_DATE_PATTERN)) {
//                    try {
//                        Date date = DateUtil.toDate(t.getDemandDate(), DateUtil.DEFAULT_DATE_PATTERN);
//                        line.setDemandDate(date);
//                    } catch (Exception e) {
//                        LOGGER.error("ArrivalNoticeServiceImpl.dateFormat", e);
//                        throw new LightKitsBizException(e);
//                    }
//                } else {
//                    LOGGER.error("ArrivalNoticeServiceImpl.dateFormat", "DemandDate Format Error");
//                }
//            } else {
//                line.setDemandDate(null);
//            }
//            if (!ObjectUtil.isNullOrEmpty(t.getItemId())) {
//                line.setItemId(Long.valueOf(t.getItemId()));
//            }
//            line.setUom(t.getUom());
//            if (!ObjectUtil.isNullOrEmpty(t.getDeliveryQty())) {
//                line.setDeliveryQty(new BigDecimal(t.getDeliveryQty()));
//            }
//            if (!ObjectUtil.isNullOrEmpty(t.getReturnedQty())) {
//                line.setReturnedQty(new BigDecimal(t.getReturnedQty()));
//            }
//            if (!ObjectUtil.isNullOrEmpty(t.getReceiveWarehouseId())) {
//                line.setReceiveWarehouseId(Long.valueOf(t.getReceiveWarehouseId()));
//            }
//            line.setLotCode(t.getLotCode());
//            line.setLineControl(t.getLineControl());
//            return line;
//        }).collect(Collectors.toList());
        return ticketLineList;
    }

    /**
     * 到货表赋值
     *
     * @param dto     source
     * @param ticketY target
     */
    private void copyTicketValue(ArrivalNoticeServiceDTO dto, WmDeliveryTicket ticketY) {
        ticketY.setOrganizationId(Long.valueOf(dto.getOrganizationId()));
        ticketY.setScmOuId(Long.valueOf(dto.getScmOuId()));
        ticketY.setRemark(dto.getRemark());
        ticketY.setPartyId(Long.valueOf(dto.getPartyId()));
        ticketY.setTicketStatus(dto.getTicketStatus());
    }

//    /**
//     * 循环遍历校验前台传来字段对象
//     * @param arrivalNoticeServiceDTOList 前台传来的参数
//     * @return result
//     */
//    private IResult checkColnum(List<ArrivalNoticeServiceDTO> arrivalNoticeServiceDTOList) {
//        if (!ObjectUtil.isNullOrEmpty(arrivalNoticeServiceDTOList)) {
//            for (ArrivalNoticeServiceDTO dto : arrivalNoticeServiceDTOList) {
//                IResult result = this.checkIntegrity(dto);
//                if (!result.isSuccessful()) {
//                    return result;
//                }
//            }
//        }
//        return new CheckResult(true);
//    }

    /**
     * 校验前台传来字段的有效性
     *
     * @param dto 单个的实体对象
     * @return result
     */
    private IResult checkIntegrity(ArrivalNoticeServiceDTO dto) {
        if (ObjectUtil.isEmpty(dto)) {
            return new CheckResult(false, "Null ArrivalNotice");
        }
        //校验到货头上必输字段
        List<ticketLineDTO> lineDTOList = dto.getTicketLineDTOList();
        if (ObjectUtil.isEmpty(dto.getTicketId())) {
            try {
                IntegrityValidator.begin().validate(dto.getOrganizationId(), "organizationId")
                        .validate(dto.getPartyId(), "partyId");
                //校验到货行上必输字段
                if (ObjectUtil.isNullOrEmpty(lineDTOList)) {
                    return new CheckResult(false, "到货行不能为空");
                }
                lineDTOList.forEach(t -> IntegrityValidator.begin().validate(t.getDeliveryQty(), "deliveryQty"));
            } catch (LightKitsBizException e) {
                return e.result();
            }
        } else {
            String ticketStatus = dto.getTicketStatus();
            if (TicketStatusEnum.EXECUTE.getValue().equalsIgnoreCase(ticketStatus)
                    ||
                    TicketStatusEnum.CANCEL.getValue().equalsIgnoreCase(ticketStatus)) {
                return IResult.fail("已执行和取消状态不能修改");
            }
        }
        return IResult.success();
    }
}
